"""K8s资源提取器工厂模块"""

from typing import Dict, Type
import logging
from src.extractors.base import Extractor

class ExtractorFactory:
    """
    提取器工厂类
    负责创建对应资源类型的提取器
    """
    
    # 存储已注册的提取器类
    _extractors: Dict[str, Type[Extractor]] = {}
    
    # 记录器
    _logger = logging.getLogger(__name__)
    
    @classmethod
    def register(cls, resource_type: str, extractor_class: Type[Extractor]) -> None:
        """
        注册提取器类
        
        Args:
            resource_type: 资源类型名称，如 'Deployment', 'Service'
            extractor_class: 对应的提取器类
        """
        cls._extractors[resource_type] = extractor_class
        cls._logger.debug(f"注册提取器: {resource_type} -> {extractor_class.__name__}")
    
    @classmethod
    def create_extractor(cls, resource_type: str) -> Extractor:
        """
        创建指定类型的提取器实例
        
        Args:
            resource_type: 资源类型名称
            
        Returns:
            对应类型的提取器实例
            
        Raises:
            ValueError: 当不支持该资源类型时
        """
        if resource_type not in cls._extractors:
            cls._logger.warning(f"未找到{resource_type}类型的提取器，尝试动态导入")
            cls._try_import_extractor(resource_type)
        
        extractor_class = cls._extractors.get(resource_type)
        if not extractor_class:
            raise ValueError(f"不支持的资源类型: {resource_type}")
        
        cls._logger.debug(f"创建{resource_type}提取器实例")
        return extractor_class()
    
    @classmethod
    def _try_import_extractor(cls, resource_type: str) -> None:
        """尝试动态导入提取器类"""
        try:
            # 尝试动态导入
            # 转换为小写模块名，例如 Deployment -> deployment
            module_name = resource_type.lower()
            module_path = f"src.extractors.{module_name}"
            
            import importlib
            module = importlib.import_module(module_path)
            
            # 假设模块中的提取器类名为 资源类型名 + "Extractor"
            extractor_class_name = f"{resource_type}Extractor"
            if hasattr(module, extractor_class_name):
                extractor_class = getattr(module, extractor_class_name)
                cls.register(resource_type, extractor_class)
                cls._logger.info(f"成功动态导入提取器: {resource_type}")
            else:
                cls._logger.error(f"找不到提取器类: {extractor_class_name}")
        except (ImportError, AttributeError) as e:
            cls._logger.error(f"导入{resource_type}提取器失败: {str(e)}")
    
    @classmethod
    def get_supported_types(cls) -> list:
        """
        获取所有支持的资源类型
        
        Returns:
            支持的资源类型列表
        """
        return list(cls._extractors.keys())
    
    @classmethod
    def is_supported(cls, resource_type: str) -> bool:
        """
        检查是否支持指定的资源类型
        
        Args:
            resource_type: 资源类型名称
            
        Returns:
            是否支持该类型
        """
        if resource_type not in cls._extractors:
            cls._try_import_extractor(resource_type)
        return resource_type in cls._extractors


# 注册所有内置提取器
def register_built_in_extractors() -> None:
    """注册内置提取器"""
    # 核心工作负载资源
    try:
        from src.extractors.deployment import DeploymentExtractor
        ExtractorFactory.register('Deployment', DeploymentExtractor)
    except ImportError:
        pass
    
    try:
        from src.extractors.statefulset import StatefulSetExtractor
        ExtractorFactory.register('StatefulSet', StatefulSetExtractor)
    except ImportError:
        pass
    
    try:
        from src.extractors.daemonset import DaemonSetExtractor
        ExtractorFactory.register('DaemonSet', DaemonSetExtractor)
    except ImportError:
        pass
    
    try:
        from src.extractors.job import JobExtractor
        ExtractorFactory.register('Job', JobExtractor)
    except ImportError:
        pass
    
    try:
        from src.extractors.cronjob import CronJobExtractor
        ExtractorFactory.register('CronJob', CronJobExtractor)
    except ImportError:
        pass
    
    # 服务发现与负载均衡资源
    try:
        from src.extractors.service import ServiceExtractor
        ExtractorFactory.register('Service', ServiceExtractor)
    except ImportError:
        pass
    
    try:
        from src.extractors.ingress import IngressExtractor
        ExtractorFactory.register('Ingress', IngressExtractor)
    except ImportError:
        pass
    
    # 配置与存储资源
    try:
        from src.extractors.configmap import ConfigMapExtractor
        ExtractorFactory.register('ConfigMap', ConfigMapExtractor)
    except ImportError:
        pass
    
    try:
        from src.extractors.secret import SecretExtractor
        ExtractorFactory.register('Secret', SecretExtractor)
    except ImportError:
        pass
    
    try:
        from src.extractors.persistentvolumeclaim import PersistentVolumeClaimExtractor
        ExtractorFactory.register('PersistentVolumeClaim', PersistentVolumeClaimExtractor)
    except ImportError:
        pass

# 注册内置提取器
register_built_in_extractors()